package com.ivan.stu.notetool.network.intercepter;

import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.ivan.stu.notetool.utils.ConstrantManager;
import com.ivan.stu.notetool.utils.EncryptUtil;


import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by IVAN on 2018/11/12.
 */

public class RequestEncryptInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        String url = chain.request().url().toString();
        Log.e("url",url);

        if (url.contains("V2")&&(url.contains("Notes"))&&!url.contains("UploadNoteSourceInfo")){  //需要加密的请求    现在笔记接口已加密  ||(url.contains("NoteTool")&& !url.contains("?"))
            //url.contains("?")

            Request request = chain.request();
            RequestBody body = request.body();
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();

            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String paramsStr = buffer.readString(charset);

            Log.e("加密前的post内容",paramsStr);
            try {
                //  paramsStr = EncryptUtils.encryptParams(paramsStr);

                //在这进行加密并形成密文；
                paramsStr = EncryptUtil.EncryptCode(ConstrantManager.childUserID,paramsStr);

            } catch (Exception e) {
                LogUtils.e(e);
            }

            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsStr);
            request = request.newBuilder()
                    .post(requestBody)
                    .build();
            return chain.proceed(request);

        }else {   //不需要加密的请求

            Request request = chain.request();
            return chain.proceed(request);
        }
    }
}
